package com.grechur.wanandroidcompose

import android.app.Application
import android.content.Context
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.grechur.wanandroidcompose.http.RetrofitClient
import okhttp3.Cookie
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.get
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.net.URL

class WanApplication : Application() {


    companion object{
        var isLogin = false
        var mContext : Context? = null
        var mLoginCookie: Cookie? = null

        fun clearLoginInfo() {
            isLogin = false
            mLoginCookie = null
            RetrofitClient.clearCookie()
        }

        fun getLoginCookie(fromLogin: Boolean) {
            if (mLoginCookie == null || fromLogin) {
                val cookiePersistor = SharedPrefsCookiePersistor(mContext)
                val loadAll = cookiePersistor.loadAll()
                loadAll.forEach { cookie ->
                    val httpUrl = "https://www.wanandroid.com/user/login".toHttpUrlOrNull()
                    httpUrl?.let {
                        if(cookie.matches(it)){
                            if (cookie.persistent) {
                                mLoginCookie = cookie
                                isLogin = true
                            }
                            return
                        }
                    }
                }
            }
        }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        mContext = base
    }

    override fun onCreate() {
        super.onCreate()
        getLoginCookie(false)
    }



}